import { defineStore } from 'pinia'
export const useLangStore = defineStore('lang', {
  namespaced: true,
  state: () => {
    return {
      langList: [], // 语言列表
      langName: '', // 当前所选语言名称
      language: ''
    }
  },
  actions: {
    updateLang (langInfo) {
      langInfo = JSON.parse(JSON.stringify(langInfo))
      const { langItemList, name, language } = langInfo
      const lang = localStorage.getItem('bbcLang')
      const langList = langItemList.filter(f => !f.hide) // 过滤掉隐藏的语言
      // 当前语言存在语言列表中
      let isExist = false
      // 是否已缓存语言
      if (lang) {
        for (const it of langList) {
          if (it.language === lang) {
            this.langName = it.name
            this.language = it.language
            isExist = true
            break
          }
        }
      }
      // 当前无缓存语言或当前缓存语言不在语言列表时
      if (!lang || !isExist) {
        this.langName = name
        this.language = language
        localStorage.setItem('bbcLang', language)
        window.location.reload()
      }
      this.langList = langList
    },
    switchLang (langInfo) {
      langInfo = JSON.parse(JSON.stringify(langInfo))
      const { name, language } = langInfo
      this.langName = name
      this.language = language
      localStorage.setItem('bbcLang', language)
    }
  }
})
